import pandas as pd
import numpy as np
import json


# 设置deadline
def get_deadline(data_frame, tr_ids):
    durations = 0
    nums = 0
    for case_id in tr_ids:
        this_df = data_frame[data_frame["case:concept:name"] == case_id]
        durations += this_df.iloc[0]["total_time_true"]
        nums += 1
    return durations / nums


# 计算活动误差
def get_act_error(data_frame, tr_ids):
    act_errors = {}
    act_nums = {}
    for case_id in tr_ids:
        this_df = data_frame[data_frame["case:concept:name"] == case_id]
        for i in range(this_df.shape[0]):
            act_name = this_df.iloc[i]["concept:name"]
            error = abs(this_df.iloc[i]["total_time_pred"] - this_df.iloc[i]["total_time_true"])
            if act_name not in act_errors:
                act_errors[act_name] = 0
                act_nums[act_name] = 0
            act_errors[act_name] += error
            act_nums[act_name] += 1
    for key in act_errors:
        act_errors[key] /= act_nums[key]
    return act_errors


if __name__ == '__main__':
    data_path = "../data/drl_data/hospital_billing/hospital_billing_w_pred.csv"
    df = pd.read_csv(data_path)

    train_ids_path = "../data/drl_data/hospital_billing/train_case_ids.npy"
    train_ids = np.load(train_ids_path)

    deadline = get_deadline(df, train_ids)
    print("Deadline is ", deadline, ".")

    activity_errors = get_act_error(df, train_ids)
    ae_js = json.dumps(activity_errors, sort_keys=False, indent=4, separators=(',', ':'))
    fw = open("../data/drl_data/hospital_billing/activity_errors.json", "w")
    fw.write(ae_js)
